import router, { asyncRoutes } from '@/router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from './utils/get-page-title'

// 白名单: 未登录也能访问的页面
const whiteList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  NProgress.start()
  const token = store.state.user.token
  if (token) {
    if (!store.getters.userid) {
      const res = await store.dispatch('user/getUserProfile')

      const filterRoutes = asyncRoutes.filter(item => {
        return res.roles.menus.includes(item.children[0].name)
      })
      // 把404加到最后一条 404 page must be placed at the end !!!
      filterRoutes.push({ path: '*', redirect: '/404', hidden: true })

      router.addRoutes(filterRoutes)
      store.commit('menu/updateMenuList', filterRoutes)
      // 解决刷新出现的白屏bug
      next({
        ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
        replace: true // 重进一次, 不保留重复历史
      })
    }
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      next()
      NProgress.done()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
      NProgress.done()
    } else {
      next('/login')
      NProgress.done()
    }
  }
  // next()
})

// 后置路由守卫
// 路由跳转完成后执行
// 也有两个参数: to, from
router.afterEach((to, from) => {
  // console.log(to, from)
  // console.log('我是后置守卫, 我执行了')
  NProgress.done()
})

